#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>
using namespace std;

template<class T>
class BlockQueue
{
public:
    static const int defaultnum=20;
    BlockQueue(int maxcap=defaultnum)
    :_maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&c_cond, nullptr);
        pthread_cond_init(&p_cond, nullptr);
        high_water=(_maxcap*2)/3;
        low_water= _maxcap/3;
    }
    T Pop()
    {
        pthread_mutex_lock(&_mutex);
        if(_q.size()==0)
        {
            pthread_cond_wait(&c_cond,&_mutex);
        }
        T out=_q.front();
        _q.pop();
        if(_q.size()<low_water)
        {
            pthread_cond_signal(&p_cond);
        }
        pthread_mutex_unlock(&_mutex);
        return out;
    }
    void Push(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        if(_q.size()==_maxcap)
        {
            pthread_cond_wait(&p_cond,&_mutex);
        }
        _q.push(in);
        if(_q.size()>high_water)
        {
            pthread_cond_signal(&c_cond);
        }
        
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&c_cond);
        pthread_cond_destroy(&p_cond);
    }

private:
    queue<T> _q;//共享资源
    pthread_mutex_t _mutex;
    pthread_cond_t  c_cond;
    pthread_cond_t  p_cond;
    int high_water;
    int low_water;
    int _maxcap;//极值
};